#include "Logger.h"
using namespace utility;

#include <iostream>
#include <time.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include <stdexcept>

const char* Logger::s_level[LEVEL_COUNT]={
        "INFO",
        "WARN",
        "ERROR"
};

Logger *Logger::m_instance = NULL;

Logger::Logger(){

}

Logger::~Logger(){

}

//生产单例对象，防止空指针
Logger * Logger::instance(){
    if(m_instance==NULL){
        m_instance = new Logger();
    }
    return m_instance;
}

void Logger::open(const std::string & filename){
    m_filename=filename;
    m_fout.open(filename,/*ios_base::out | */std::ios_base::app);
    if(m_fout.fail()){
        throw std::logic_error("open file failed"+filename);
    }
}

void Logger::close(){
    m_fout.close();
}

void Logger::log(Level level,const char *file,const char *line,const char *format,...){
    if(m_fout.fail()){
        throw std::logic_error("open file failed"+m_filename);
    }
    //记录时间
    time_t ticks =time(NULL);
    struct tm *ptm=localtime(&ticks);
    char timestamp[32];
    memset(timestamp,0,sizeof(timestamp));
    strftime(timestamp,sizeof(timestamp),"%Y-%m-%d %H:%M:%S",ptm);
    //规定格式
    const char *fmt="%s %s %s:%d";
    //获取长度动态的创造buf
    int size=snprintf(NULL,0,fmt,timestamp,s_level[level],file,line);
    if(size>0){
        char *buffer=new char[size+1];
        snprintf(buffer,size+1,fmt,timestamp,s_level[level],file,line);
        buffer[size]=0;
        m_fout<<buffer;
        delete buffer;
    }
    //将可变参数传入文件中

    va_list arg_ptr;
    va_start(arg_ptr,format);
    size=vsnprintf(NULL,0,format,arg_ptr);
    va_end(arg_ptr);
    if(size>0){
        char *content=new char[size+1];
        va_start(arg_ptr,format);
        vsnprintf(content,sizeof+1,format,arg_ptr);
        va_end(arg_ptr);
        std::cout<<content<<std::endl;
        m_fout<<content;
    }
    m_fout<<"\n";
    m_fout.flush();
}
//如何记录如下
//Logger::instance()->open("filename");
//Logger::instance()->log(Logger::DEGUG,__FILE__,__FILE__,"你想传入的内容")
//or用debug（format）代替log函数